<template>
  <div class="bar-container"></div>
</template>

<script>

const echarts = require('echarts/lib/echarts')
require('echarts/lib/chart/bar')
require('echarts/lib/component/legend')
require('echarts/lib/component/title')

export default {
  props: {
    option: {
      type: Object,
      required: true
    },
    hasClick:{
      type:Boolean,
      default:false
    }
  },
  data () {
    return {
      chart: null
    }
  },
  watch: {
    option: {
      immediate: true,
      deep: true,
      handler () {
        if (!this.option) { return }
        if (!this.$el) {
          this.$on('hook:mounted', this.initChart)
        } else {
          this.initChart()
        }
      }
    }
  },
  beforeDestroy () {
    if (this.cahrt) {
      this.chart.dispose()
      this.chart = null
    }
  },
  methods: {
    initChart () {
      if (!this.chart) {
        this.chart = echarts.init(this.$el)
      }
      this.chart.setOption(this.option)
      if(this.hasClick){
        this.chart.on('click', (param) => {
          this.pointClick(param);
        });
      }
     
    },
    pointClick(param){
      if(param.name){
        this.$emit('barChange',param.name)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.bar-container {
  width: 100%;
  height: 100%;
  position: relative;
}
</style>
